package com.neu.servletsession;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Servlet implementation class SessionServlet
 */
@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Object text;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");//  响应的编码集
		request.setCharacterEncoding("utf-8");				//请求的编码集
		String text = request.getParameter("text");
		/*
		 *  将获取的数据存储到 session 对象中
		 *  	HttpSession 是一个接口，不能直接实例化，
		 *  通常会通过 request.getSession()方法获取；
		 */
		HttpSession session =  request.getSession();
		/*
		 * 将 test 的存储到 session 对象中 (session 也是一个域对象)
		 */
		session.setAttribute("text",text);
		/*
		 *  重定向到新的页面 ， session中存储的值一样可以获取
		 */
		//response.sendRedirect("testSession.jsp"); //和下面的代码功能一样
		/*
		 * RequestDispatcher rd = request.getRequestDispatcher("testSession.jsp")；
		 * rd.forward(request, response)  等同于下面的代码
		 */
		request.getRequestDispatcher("testSession.jsp").forward(request, response);
	}	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
